package com.xx.happychatboot.middleware.springsecurity.security;

import cn.hutool.core.collection.CollectionUtil;
import com.xx.happychatboot.serve.user.domain.entity.SysRole;
import com.xx.happychatboot.serve.user.domain.entity.SysUser;
import com.xx.happychatboot.serve.user.service.ISysRoleService;
import com.xx.happychatboot.serve.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 根据用户名加载用户信息
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.loadUserByUsername(username);
        if(Objects.isNull(user)) {
            throw new RuntimeException("⽤户不存在");
        }
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user.getUserId());
        userDetail.setUsername(user.getUsername());
        userDetail.setPassword(user.getPassword());
        userDetail.setAccountNonExpired(user.getAccountNonExpired());
        userDetail.setAccountNonLocked(user.getAccountNonLocked());
        userDetail.setCredentialsNonExpired(user.getCredentialsNonExpired());
        userDetail.setEnabled(user.getEnabled());
        List<SysRole> roles = roleService.getRolesByUid(user.getUserId());
        if (CollectionUtil.isNotEmpty(roles)) {
            userDetail.setRoles(roles);
        }
        return userDetail;
    }
}
